import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
import { Index } from '../../../apis/index.js';
import util from "../../../utils/util";
const app = getApp();
const API = new Index();
let computeOrderCostTime = null;
WXPage({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    contentHeight: 0,
    listdata: [],
    //数据
    pageNum: 1,
    pageSize: 10,
    showMoreVisable: false,
    StatusMap: {
      1: '待处理',
      2: '待处理',
      3: '待处理',
      4: '待处理',
      5: '处理中',
      6: '已处理'
    },
    TypeMap: {
      1: '清扫',
      2: '日用品更换',
      3: '维修',
      4: '处理呼叫服务',
      5: '开票',
      6: '续住',
      7: '退房通知',
      8: '消费券',
      9: '好评有礼'
    },
    workStatus: 0
  },
  onLoad: function (options) {
    this.setData({
      // contentHeight: app.globalData.windowH - 88 *app.globalData.windowW /750
      contentHeight: app.globalData.windowH - this.data.CustomBar - 130
    });
  },
  // 计算订单时长与费用
  computeOrderCost(list) {
    let clearIntervalOff = true;
    for (let item of list) {
      let t = '0分钟';
      let money = 0;
      if (item.state === 2) {
        let timeLen = parseInt((new Date().getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000);
        timeLen = timeLen > 0 ? timeLen : 0;
        let {
          h,
          m,
          s
        } = util.secondToTime(timeLen > 0 ? timeLen : 0);
        t = `${h}时${m}分`;
        if (item.feeMode === 1) {
          money = item.priceTypeInfo.payIntervalPrice / (item.priceTypeInfo.payInterval * 60) * timeLen;
          if (money > item.priceTypeInfo.maxPayPrice) money = item.priceTypeInfo.maxPayPrice;
          money = (money / 100).toFixed(2);
        } else money = (item.priceTypeInfo.useDuration / 100).toFixed(2);
        clearIntervalOff = false;
      } else if (item.state === 5) {
        let timeLen = parseInt((new Date(item.endAt.replace(/\-/g, '/')).getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000);
        timeLen = timeLen > 0 ? timeLen : 0;
        let {
          h,
          m,
          s
        } = util.secondToTime(timeLen > 0 ? timeLen : 0);
        t = `${h}时${m}分`;
      }
      item.useTime = t;
      if (money) item.settlementMoneyStr = money;else if (!item.settlementMoneyStr || item.state !== 5) item.settlementMoneyStr = '0.00';
    }
    clearInterval(computeOrderCostTime);
    if (!clearIntervalOff) computeOrderCostTime = setInterval(ev => this.computeOrderCost(list), 1000);
    this.setData({
      listdata: list
    });
  },
  getOrderList: function (pageNum) {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    var param = {
      pageNo: pageNum,
      pageSize: this.data.pageSize,
      status: this.data.workStatus
    };
    if (param.pageNo === 1) this.data.listdata = [];
    API.getWorkList(param).then(res => {
      wx.hideLoading();
      for (let item of res.result.data || []) if (item.notificationType === 5) {
        try {
          let {
            money,
            phone,
            taxCode,
            unitName
          } = JSON.parse(item.info);
          item.money = money;
          item.phone = phone;
          item.taxCode = taxCode;
          item.unitName = unitName;
        } catch (err) {
          item.money = '';
          item.phone = '';
          item.taxCode = '';
          item.unitName = '';
        }
      }
      var listData = this.data.listdata.concat(res.result.data);
      var showMore = false;
      if (res.result.totalCount > listData.length) {
        showMore = true;
      }
      // listData = listData.concat(listData,listData,listData, listData,listData)
      this.setData({
        listdata: listData,
        showMoreVisable: showMore
      });
    });
  },
  // 状态更新查询
  updateOrderList(ev) {
    ev.mark = ev.target.dataset
    this.setData({
      workStatus: ev.mark.status,
      pageNum: 1
    });
    this.getOrderList(1);
  },
  // 显示更多
  showMore: function () {
    var pageNum = this.data.pageNum += 1;
    console.log(pageNum);
    this.getOrderList(pageNum);
  },
  // openDetail: function() {
  //   wx.navigateTo({
  //     url: '../orderdetail/orderdetail',
  //   })
  // }
  // 结束订单，结束使用
  closeOrder: function (e) {
    var loginInfo = wx.getStorageSync('login_key');
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否结束订单',
      success(res) {
        if (res.confirm) {
          var param = {
            "deviceSn": e.currentTarget.dataset.devicesn,
            "productId": e.currentTarget.dataset.productid,
            "openid": loginInfo.openid,
            "tradeNo": e.currentTarget.dataset.trade
          };
          API.closeOrder(param).then(res => {
            // wx.showToast({
            //   title: '已归还',
            // })
            wx.redirectTo({
              url: '/pages/orderDetail/orderDetail?settMoney=' + res.result.settMoney + '&useTime=' + res.result.useTime + '&returnMoney=' + res.result.returnMoney + '&productId=' + that.data.orderInfo.productId + '&deviceSn=' + e.currentTarget.dataset.devicesn
            });
            // wx.redirectTo({
            //   url: '/pages/orderDetail/orderDetail?settMoney=' + res.result.settMoney + '&useTime=' + res.result.useTime + '&returnMoney=' + res.result.returnMoney,
            // })
          });
        } else if (res.cancel) {}
      }
    });
    that.onShow();
  },
  onShow: function () {
    this.getOrderList(this.data.pageNum);
  },
  onHide: function () {
    clearInterval(computeOrderCostTime);
  },
  onUnload: function () {
    clearInterval(computeOrderCostTime);
  },
  getHistory: function () {
    wx.navigateTo({
      url: '/pages/mine/history/history'
    });
  },
  // 跳转详情
  toDeatail(ev) {
    ev.mark = ev.target.dataset
    let {
      id,
      commentId,
      notificationType
    } = ev.mark.item;
    wx.navigateTo({
      url: `/pages/workOrderDetail/workOrderDetail?id=${id}&commentId=${commentId}&notificationType=${notificationType}`
    });
  }
});

// pages/order/history/history.js
// Page({
//
//   /**
//    * 页面的初始数据
//    */
//   data: {
//
//   },
//
//   /**
//    * 生命周期函数--监听页面加载
//    */
//   onLoad: function (options) {
//
//   },
//   // 订单异常
//   toRepairs() {
//     wx.navigateTo({
//       url: '/pages/report/report',
//     })
//   },
//   // 跳转详情
//   toDeatail() {
//     wx.navigateTo({
//       url: '/pages/mine/orderdetail/orderdetail',
//     })
//   },
// })
